import tkinter as tk
from tkinter import *
from tkinter.messagebox import *
import time
#from datetime import datetime
from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg
from matplotlib.figure import Figure
import numpy as np
import matplotlib.animation as animation
from dev.A8 import A8
from SQL.A8 import A8 as a8_sql

class chartPageA8(object):
    def __init__(self, master=None, interval=1000):
        self.root = master
        print(self.root.baudrate)
        self.x = np.array([])
        self.y = np.array([]).reshape(0, 8)
        self.anim = None
        self.interval = interval
        #self.createPage()
    # 定义动态更新的数据函数
    def update_data(self):
        a8 = A8(self.root.port,self.root.baudrate,self.root.slave)
        # d = a8.read_random() # for test
        d = a8.read_reg()
        if d == []:
            self.anim.event_source.stop()
            showinfo(title='提示', message='无法读取数据')
        else:
            d.append(time.strftime('%Y-%m-%d %H:%M:%S',time.localtime()))
            a8_sql().add(d)
            self.label_A1.config(text='A1:'+str(d[0]))
            self.label_A2.config(text='A2:'+str(d[1]))
            self.label_A3.config(text='A3:'+str(d[2]))
            self.label_A4.config(text='A4:'+str(d[3]))
            self.label_A5.config(text='A5:'+str(d[4]))
            self.label_A6.config(text='A6:'+str(d[5]))
            self.label_A7.config(text='A7:'+str(d[6]))
            self.label_A8.config(text='A8:'+str(d[7]))

            self.x = np.append(self.x, time.strftime('%H:%M:%S', time.localtime()))
            self.y = np.append(self.y, [d[:8]], axis=0)

            if len(self.y) > 30:
                self.y = self.y[1:]
                self.x = self.x[1:]
    # 定义绘制图表的函数
    def plot_curve(self,frame):
        self.update_data()
        self.ax.clear()  # 清除之前的图
        self.fig.autofmt_xdate(rotation=45)
        #self.ax.tick_params(axis='x', labelrotation=45)
        # print(self.y[:,0])
        self.ax.plot(self.x,self.y[:,0],ls = '-',marker = 'o',color = 'blue')  # 绘制新的图
        self.ax.plot(self.x,self.y[:,1],ls = '-',marker = 'o',color = 'red')
        self.ax.plot(self.x,self.y[:,2],ls = '-',marker = 'o',color = 'gray')
        self.ax.plot(self.x,self.y[:,3],ls = '-',marker = 'o',color = 'orange')
        self.ax.plot(self.x,self.y[:,4],ls = '-',marker = 'o',color = 'purple')
        self.ax.plot(self.x,self.y[:,5],ls = '-',marker = 'o',color = 'black')
        self.ax.plot(self.x,self.y[:,6],ls = '-',marker = 'o',color = 'yellow')
        self.ax.plot(self.x,self.y[:,7],ls = '-',marker = 'o',color = 'green')

        self.ax.set_xlabel('Time(s)')
        self.ax.set_ylabel('Current(mA)')
        self.ax.set_title('ZSKJ-A8 Real-time Data')
        self.ax.grid(True)
        self.canvas.draw()  # 重绘图表
    def createPage(self):
        self.newWindow = tk.Toplevel(self.root)
        self.newWindow.title("A8 Chart")
        self.newWindow.geometry("800x600")
        # self.label = tk.Label(self.newWindow, text='实时数据: ')
        # self.label.pack()
        # 初始化Figure和FigureCanvas
        self.fig = Figure(figsize=(5, 5), dpi=100)
        self.canvas = FigureCanvasTkAgg(self.fig, master=self.newWindow)
        self.canvas.draw()
        self.canvas.get_tk_widget().pack(side=tk.TOP, fill=tk.BOTH, expand=1)

        font = ('SimHei',16)
        self.label_A1 = tk.Label(self.newWindow, text='A1',font=font,fg='blue')
        self.label_A1.pack(side=tk.LEFT, fill=tk.X, expand=1)
        self.label_A2 = tk.Label(self.newWindow, text='A2',font=font,fg='red')   
        self.label_A2.pack(side=tk.LEFT, fill=tk.X, expand=1)
        self.label_A3 = tk.Label(self.newWindow, text='A3',font=font,fg='gray')
        self.label_A3.pack(side=tk.LEFT, fill=tk.X, expand=1)
        self.label_A4 = tk.Label(self.newWindow, text='A4',font=font,fg='orange')
        self.label_A4.pack(side=tk.LEFT, fill=tk.X, expand=1)
        self.label_A5 = tk.Label(self.newWindow, text='A5',font=font,fg='purple')
        self.label_A5.pack(side=tk.LEFT, fill=tk.X, expand=1)
        self.label_A6 = tk.Label(self.newWindow, text='A6',font=font,fg='black')
        self.label_A6.pack(side=tk.LEFT, fill=tk.X, expand=1)
        self.label_A7 = tk.Label(self.newWindow, text='A7',font=font,fg='yellow')
        self.label_A7.pack(side=tk.LEFT, fill=tk.X, expand=1)
        self.label_A8 = tk.Label(self.newWindow, text='A8',font=font,fg='green')
        self.label_A8.pack(side=tk.LEFT, fill=tk.X, expand=1)
        
        # 创建一个图表和一个轴
        self.ax = self.fig.add_subplot(1,1,1)
        # 使用FuncAnimation来动态更新图表
        self.anim = animation.FuncAnimation(self.fig, self.plot_curve, frames=1, interval=self.interval,repeat_delay=self.interval)

if __name__ == '__main__':
    root = tk.Tk()
    root.title("Chart master")
    root.geometry("800x600")
    root.baudrate = 9600
    chart = chartPageA8(root,interval=1000)
    chart.createPage()
    root.mainloop()